<template>
  <Dialog v-model="dialogVisible" title="分配门店">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" label-width="80px">
      <el-form-item label="用户名称">
        <el-input v-model="formData.username" :disabled="true" />
      </el-form-item>
      <el-form-item label="用户昵称">
        <el-input v-model="formData.nickname" :disabled="true" />
      </el-form-item>
      <el-form-item label="门店" prop="storeIds">
        <div class="store-checkbox-container">
          <el-checkbox
            v-model="selectAll"
            @change="handleSelectAll"
            :indeterminate="isIndeterminate"
          >
            全选
          </el-checkbox>
          <el-divider />
          <div class="store-list">
            <el-checkbox-group v-model="formData.storeIds" @change="handleStoreChange">
              <el-checkbox
                v-for="item in storeList"
                :key="item.storageId"
                :label="item.storageId"
                class="store-checkbox-item"
              >
                {{ item.storageName }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as UserApi from '@/api/system/user'
import { BaseStorageApi } from '@/api/crm/basestorage'

defineOptions({ name: 'SystemUserAssignStoreForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: -1,
  nickname: '',
  username: '',
  storeIds: [] as number[]
})
const formRef = ref() // 表单 Ref
const storeList = ref([] as any[]) // 门店的列表
const selectAll = ref(false) // 全选状态
const isIndeterminate = ref(false) // 半选状态

/** 打开弹窗 */
const open = async (row: UserApi.UserVO) => {
  dialogVisible.value = true
  resetForm()
  // 设置数据
  formData.value.id = row.id
  formData.value.username = row.username
  formData.value.nickname = row.nickname

  // 获得门店列表
  formLoading.value = true
  try {
    // 先加载门店列表
    const response = await BaseStorageApi.getBaseStorageAllDesc()
    storeList.value = response || []
    console.log('门店列表:', storeList.value)

    // 等待DOM更新
    await nextTick()

    // 获取用户已分配的门店
    const userStores = await UserApi.getUserStoreList({ userId: row.id })
    console.log('用户已分配门店:', userStores)

    // 设置用户已分配的门店ID
    const userStoreIds = userStores.map((item: any) => Number(item.nodeId))
    formData.value.storeIds = userStoreIds
    console.log('设置的门店ID:', formData.value.storeIds)

    // 再次等待DOM更新后更新全选状态
    await nextTick()
    updateSelectAllStatus()
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    // 调用保存用户门店权限接口
    await UserApi.saveUserStoreAuth({
      userId: formData.value.id,
      storeIds: formData.value.storeIds,
      dataTypeId: 1
    })
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success', true)
  } catch (error) {
    console.error('保存用户门店权限失败:', error)
    message.error('保存失败，请重试')
  } finally {
    formLoading.value = false
  }
}

/** 全选/取消全选 */
const handleSelectAll = (val: boolean) => {
  if (val) {
    formData.value.storeIds = storeList.value.map((item) => item.storageId)
  } else {
    formData.value.storeIds = []
  }
  updateSelectAllStatus()
}

/** 门店选择变化处理 */
const handleStoreChange = (value: number[]) => {
  console.log('门店选择变化处理:', value)
  formData.value.storeIds = value
  updateSelectAllStatus()
}

/** 更新全选状态 */
const updateSelectAllStatus = () => {
  const checkedCount = formData.value.storeIds.length
  const totalCount = storeList.value.length

  console.log('更新全选状态:', {
    checkedCount,
    totalCount,
    storeIds: formData.value.storeIds,
    storeList: storeList.value.map((item) => item.storageId)
  })

  // 如果没有门店列表，重置全选状态
  if (totalCount === 0) {
    selectAll.value = false
    isIndeterminate.value = false
    return
  }

  // 确保所有门店都被选中时才显示全选
  const allStoreIds = storeList.value.map((item) => item.storageId)
  const allSelected =
    allStoreIds.length > 0 && allStoreIds.every((id) => formData.value.storeIds.includes(id))

  selectAll.value = allSelected
  isIndeterminate.value = checkedCount > 0 && checkedCount < totalCount

  console.log('全选状态:', {
    selectAll: selectAll.value,
    isIndeterminate: isIndeterminate.value,
    allSelected
  })
}

/** 监听门店选择变化 */
watch(
  () => formData.value.storeIds,
  (newVal, oldVal) => {
    console.log('门店选择变化:', { newVal, oldVal })
    // 使用nextTick确保DOM更新后再更新状态
    nextTick(() => {
      updateSelectAllStatus()
    })
  },
  { deep: true, immediate: true }
)

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: -1,
    nickname: '',
    username: '',
    storeIds: []
  }
  storeList.value = []
  selectAll.value = false
  isIndeterminate.value = false
  formRef.value?.resetFields()
}
</script>

<style scoped>
.store-checkbox-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.store-checkbox-item {
  display: inline-block;
  border-radius: 4px;
  transition: background-color 0.2s;
  min-width: 120px;
}

.store-checkbox-item:hover {
  background-color: #f5f7fa;
}
</style>
